import { ref, getCurrentInstance, unref, nextTick } from "vue";
import { TimeInstance, Nullable, TimeGpProps } from "./type";
export function useTimeGroup(props: TimeGpProps): any {
  if (!getCurrentInstance()) {
    throw new Error(
      "useTimeGroup() can only be used inside setup() or functional components!"
    );
  }

  const timeInstanceRef = ref<Nullable<any>>(null);
  const loaded = ref(false);

  function register(TimeInstance: TimeInstance) {
    if (unref(loaded)) {
      return;
    }
    TimeInstance.setProps(props);
    timeInstanceRef.value = TimeInstance;
    loaded.value = true;
  }

  const getInstance = () => {
    const instance = unref(timeInstanceRef);
    if (!instance) {
      throw new Error("insatnce is undefined");
    }
    return instance;
  };

  async function getValue() {
    await nextTick();
    return getInstance()?.getValue();
  }

  return [register, { getValue }];
}
